import { Body, Controller, Post, UploadedFile, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { FileFieldsInterceptor, FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiProperty, ApiQuery, ApiTags } from '@nestjs/swagger';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { FileUploadDto, FileUploadDtos } from 'src/dto/FileUpload.dto';
@Controller('file-upload')
@ApiTags("file-upload")
export class FileUploadController {
    @Post('upload')
    @ApiConsumes('multipart/form-data')
    @UseInterceptors(FileInterceptor('file'))
    @ApiBody({
        description: 'file',
        type: FileUploadDto,
    })
    uploadFile(@UploadedFile() file: Express.Multer.File, @Body() body) {
        console.log(body);
        console.log(file);
        console.log('process.cwd() :>> ', process.cwd());
        let path_ = join(process.cwd(), './src', './public/upload', `${file.originalname}`);
        console.log('path_ :>> ', path_);
        const writeImage = createWriteStream(path_);
        writeImage.write(file.buffer)
        return '上传成功';
    }


    @Post('doAddAll')
    @ApiConsumes('multipart/form-data')
    @UseInterceptors(FileFieldsInterceptor([
        { name: 'avatar', maxCount: 1 },
        { name: 'background', maxCount: 1 },
    ]))
    @ApiBody({
        description: 'files',
        type: FileUploadDtos,
    })
    addAllUser(@UploadedFiles() uploads: { avatar?: Express.Multer.File[], background?: Express.Multer.File[] }) {
        for (const filename in uploads) {
            const files = uploads[filename];
            for (const file of files) {
                let path_ = join(process.cwd(), './src', './public/upload', `${file.originalname}`);
                const writeImage =
                    createWriteStream(path_);
                writeImage.write(file.buffer);
            }
        }
        return '上传成功';
    }
}
